import { VirtualChild, VirtualChildParam } from "./virtualTreeChildren"
import { BuildResult, getAsOne, mve } from "./util"

/**重复的函数节点/组件封装成mve*/
export interface EOChild<EO> {
	(parent: VirtualChild<EO>, me: mve.LifeModel): BuildResult
}
export function refreshInit(result?: BuildResult) {
	if (result) {
		return function () {
			const destroy = result()
			if (destroy) {
				if (typeof (destroy) == 'function') {
					return destroy
				} else {
					console.warn(`ChildLife返回不是函数，不视为生命周期函数`, destroy, this)
				}
			}
		}
	}
	return result
}
export interface FragmentNode<EO> {
	init?: BuildResult,
	children: EOChild<EO>[]
}
/**
 * 片段自定义组件
 * @param config 
 * @param children 
 * @returns 
 */
export function fragment<EO>(p: FragmentNode<EO>): EOChild<EO> {
	const init = refreshInit(p.init)
	const children = p.children
	return function (parent, me) {
		const outs: BuildResult[] = []
		if (init) {
			outs.push(init)
		}
		for (const child of children) {
			const out = baseChildrenBuilder(me, child, parent)
			if (out) {
				outs.push(out)
			}
		}
		return getAsOne(outs)
	}
}
export interface OriginalNode<EO> {
	init?: BuildResult,
	children: EO[]
}
/**
 * 原生组件
 * @param config 
 * @param children 
 */
export function original<EO>(p: OriginalNode<EO>): EOChild<EO> {
	const init = refreshInit(p.init)
	const children = p.children
	return function (parent) {
		for (const child of children) {
			parent.push(child)
		}
		return init
	}
}
export function baseChildrenBuilder<EO>(me: mve.LifeModel, children: EOChild<EO>, parent: VirtualChild<EO>) {
	return children(parent.newChildAtLast(), me)
}
export function childrenBuilder<EO>(me: mve.LifeModel, x: VirtualChildParam<EO>, children: EOChild<EO>[]) {
	const outs: BuildResult[] = []
	const root = VirtualChild.newRootChild(x)
	for (const child of children) {
		const out = baseChildrenBuilder(me, child, root)
		if (out) {
			outs.push(out)
		}
	}
	return getAsOne(outs)
}